package com.gxuwz.zhangjiahui.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.zhangjiahui.entity.Limit;
import com.gxuwz.zhangjiahui.entity.Role;
import com.gxuwz.zhangjiahui.entity.User;
import com.gxuwz.zhangjiahui.service.ILimitService;
import com.gxuwz.zhangjiahui.service.IRoleService;
import org.apache.ibatis.annotations.Param;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zhangjiahui
 * @since 2021-06-20
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService iRoleService;
    @Autowired
    private ILimitService iLimitService;


    /**
     * 查询全部角色信息
     * @param modelAndView
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/findRole")
    public ModelAndView findRole(ModelAndView modelAndView, Page page, Integer pageNumber,
                                    @Param("roleId") String roleId,
                                    HttpServletRequest request, HttpServletResponse response) {
        if(request.getSession().getAttribute("nowResult") != null){
            if (!request.getSession().getAttribute("nowResult").equals("now")) {
                request.getSession().setAttribute("result", "");
            }
            request.getSession().setAttribute("nowResult", "");
        }
        // 可以通过 wrapper 进行筛选!!!
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.orderByAsc("role_id");
        String[] keysWord = null;
        // 对User进行模糊查询!!!
        if(roleId != null && roleId != ""){
            wrapper.like("role_id", roleId);
            request.getSession().setAttribute("roleId", roleId);
        }else {
            request.getSession().setAttribute("roleId", "");
        }
        // Current,页码 + Size,每页条数
        if(pageNumber == null){
            page.setCurrent(1);
        }else {
            page.setCurrent((long)pageNumber);
        }
        // 默认每页6行数据！
        page.setSize(6);
        // 调用分页查询方法！!
        IPage<Role> roleIPage = iRoleService.selectRolePage(page, wrapper);
        // 存放一个数组用来让foreach遍历
        int[] pagesList = new int[(int)roleIPage.getPages()];
        for(int i=0; i< (int)roleIPage.getPages(); i++){
            pagesList[i] = i+1;
        }
        modelAndView.addObject("pagesList", pagesList);
        modelAndView.addObject("numberPages", roleIPage.getTotal());
        // 存放page，内有当前页数
        modelAndView.addObject("page", page);
        System.out.println("总条数"+roleIPage.getTotal());
        System.out.println("总页数"+roleIPage.getPages());
        // 存放总页数
        modelAndView.addObject("pages", (int)roleIPage.getPages());
        List<Role> roleList = roleIPage.getRecords();
        System.out.println("roleList = "+roleList);
        modelAndView.addObject("roleList", roleList);

        // 修改气泡提示框的文本输入
        List<Role> roleList2 = iRoleService.findRoleAll();
        for(int i=0; i < roleList2.size(); i++){
            String[] roleListTexts = roleList2.get(i).getRoleLimit().split(",");
            String roleListText = "已有 " + roleListTexts.length + "条 权限";
            roleList2.get(i).setRoleLimit(roleListText);
        }
        modelAndView.addObject("roleList2", roleList2);

        // 存放查询到的全部权限
        List<Limit> limitList = iLimitService.findLimitAll();
        modelAndView.addObject("limitLists", limitList);

        // 查询全部角色
        List<Role> roleList1 = iRoleService.findRoleAll();
        modelAndView.addObject("roleList", roleList1);

        modelAndView.setViewName("role/role_list");
        return modelAndView;
    }


    /**
     * 跳转进入新增角色界面
     * @param modelAndView
     * @return
     */
    @RequestMapping(value = "/insertRole")
    public ModelAndView insertRole(ModelAndView modelAndView, HttpServletRequest request) {
        // 存放查询到的全部权限
        List<Limit> limitList = iLimitService.findLimitAll();
        modelAndView.addObject("limitLists", limitList);
        modelAndView.setViewName("role/role_add");
        return modelAndView;
    }

    /**
     * 添加角色信息
     * @param modelAndView
     * @param role
     * @return
     */
    @RequestMapping(value = "/addRole")
    public ModelAndView addRole(ModelAndView modelAndView, Role role, HttpServletRequest request) {
        // 获取checkbox的内容
        String[] checkbox=request.getParameterValues("checkbox");
        String str = "";
        Limit limit = new Limit();
        for(int i=0;i< checkbox.length; i++){
            limit.setId(Integer.valueOf(checkbox[i]));
            Limit limit1 = iLimitService.findLimitById(limit);
            str += limit1.getLimitId() + ",";
        }
        // 对str进行尾部处理，出去里面的值
        str.substring(0, str.length()-1);
        role.setRoleLimit(str);
        // 查找是否存在该角色
        Role role1 = iRoleService.findRoleById(role);
        if(role1 == null){
            // 修改角色信息
            iRoleService.addRole(role);
            request.setAttribute("result", "addTrue");
            request.getSession().setAttribute("nowResult", "now");
        }else {
            request.setAttribute("result", "addFalse");
            request.getSession().setAttribute("nowResult", "now");
        }
        modelAndView.setViewName("redirect:/role/findRole");
        return modelAndView;
    }

    /**
     * 跳转进入修改角色界面
     * @param modelAndView
     * @param roleId
     * @return
     */
    @RequestMapping(value = "/updateRole")
    public ModelAndView updateRole(ModelAndView modelAndView, @Param("roleId") String roleId, HttpServletRequest request) {
        // 存放查询到的全部权限
        List<Limit> limitList = iLimitService.findLimitAll();
        modelAndView.addObject("limitLists", limitList);
        Role role = new Role();
        role.setRoleId(roleId);
        Role role1 = iRoleService.findRoleById(role);
        modelAndView.addObject("role", role1);
        // 获取对应角色的权限
        String linits = role1.getRoleLimit();
        String[] strs = linits.split(",");
        modelAndView.addObject("strs", strs);
        modelAndView.setViewName("role/role_edit");
        return modelAndView;
    }

    /**
     * 修改角色信息
     * @param modelAndView
     * @param role
     * @return
     */
    @RequestMapping(value = "/editRole")
    public ModelAndView editRole(ModelAndView modelAndView, Role role, HttpServletRequest request) {
        // 获取checkbox的内容
        String[] checkbox = request.getParameterValues("checkbox");
        String str = "";
        Limit limit = new Limit();
        for(int i=0;i< checkbox.length; i++){
            limit.setId(Integer.valueOf(checkbox[i]));
            Limit limit1 = iLimitService.findLimitById(limit);
            str += limit1.getLimitId() + ",";
        }
        // 对str进行尾部处理，出去里面的值
        str.substring(0, str.length()-1);
        role.setRoleLimit(str);
        // 修改角色信息
        iRoleService.updateRoleById(role);
        request.setAttribute("result", "editTrue");
        request.getSession().setAttribute("nowResult", "now");
        modelAndView.setViewName("redirect:/role/findRole");
        return modelAndView;
    }



    /**
     * 删除用户信息
     * @param roleId
     * @return
     */
    @GetMapping(value = "/deleteRole")
    public ModelAndView deleteRole(HttpServletRequest request, ModelAndView modelAndView,
                             @Param("roleId") String roleId) {
        Role role = new Role();
        role.setRoleId(roleId);
        try {
            iRoleService.deleteRoleById(role);
            request.getSession().setAttribute("result", "deleteTrue");
            request.getSession().setAttribute("nowResult", "now");
        }catch (Exception e){

        }
        modelAndView.setViewName("redirect:/role/findRole");
        return modelAndView;
    }

}
